package com.fruit.interceptor;

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fruit.pojo.user.UserInfo;
import com.fruit.pojo.user.UserLogin;
import com.fruit.resolver.DefiniteException;
import com.fruit.service.user.UserManager;
import com.fruit.util.CustomUtil;
import com.fruit.util.MessagesCode;
import com.fruit.util.ResultInfo;
import com.fruit.util.ResultUtil;



public class AppLoginSecurityInterceptor extends HandlerInterceptorAdapter {
	
	@Value("${app.key}")
	private String key;
	
	@Resource(name = "userService")
	private UserManager userService;
	
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		response.setContentType("text/html;charset=UTF-8");
		try {
			String signLogin = request.getParameter("signLogin");
			boolean isLogin = false;
			String loginId = "";
			System.out.println("登录验证开始");
			if (StringUtils.isNotEmpty(signLogin)){
				loginId = request.getParameter("loginId");
				String nonce = request.getParameter("nonce");
				String timestamp = request.getParameter("timestamp");
				UserLogin login = userService.getUserLoginById(Integer.parseInt(loginId));
				if(login != null){
					Map<String, String> paramsO = new TreeMap<String, String>();
					paramsO.put("userName", login.getUserName());
					paramsO.put("pwd", login.getPwd());
					paramsO.put("nonce", nonce);
					paramsO.put("timestamp", timestamp);
					String mySign = CustomUtil.createSign(paramsO,key);
					if (StringUtils.equals(signLogin.toUpperCase(), mySign)) {
						isLogin = true;
					}
				}

			}
			if(!isLogin){
					Map<String, Object> resMap = new HashMap<String, Object>();
					ResultInfo ri = ResultUtil.initResult(ResultInfo.ERROR, MessagesCode.LOGIN_OUT, "用户未登录");
					ri.setIsAgainLogin("01");
					resMap.put("result", ri);
					ObjectMapper om = new ObjectMapper();
					response.getWriter().print(om.writeValueAsString(resMap));
				
			}
			UserInfo user = userService.getUserInfoByLoginId(Integer.parseInt(loginId));
			
			if (!"01".equals(user.getState())) {
				String msg = "该用户已经被禁用，请联系管理员";
				Map<String, Object> resMap = new HashMap<String, Object>();
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "exception", msg));
				ObjectMapper om = new ObjectMapper();
				response.getWriter().print(om.writeValueAsString(resMap));
			}
			
			return isLogin;
		}catch(Exception e){
			
			return false;
		}
	}

}
